import {
  FC,
  ForwardRefExoticComponent,
  PropsWithoutRef, RefAttributes,
  useEffect,
  useRef,
  useState,
} from "react";
import { WrappedComponentProps } from "../../pro-hoc/withModal"
import {ProBox} from '../../pro-box';
import { DataAction, OnError, CreateOrEditActionRef } from '../typing';

export interface CreateOrEditProps extends WrappedComponentProps {
  rowKey?: string | number;
  CreateOrEditContent?: ForwardRefExoticComponent<PropsWithoutRef<{ rowKey: string | number, values: any }> & RefAttributes<CreateOrEditActionRef>>;
  dataAction: DataAction;
  onError: OnError;
}

const CreateOrEdit: FC<CreateOrEditProps> = ({ rowKey, CreateOrEditContent, dataAction, onError, modalControl }) => {
  const actionRef = useRef<CreateOrEditActionRef>();
  const [errorMsg, setErrorMsg] = useState<any>();
  const [values, setValues] = useState<any>({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const disposeErr = (e: any) => {
      const errMsg = e.msg || e.message
      setErrorMsg(errMsg)
      setLoading(false)
      onError(errMsg)
    }

    if (rowKey !== undefined && rowKey) {
      dataAction.getItem(rowKey).then((data) => {
        setValues(data);
        setLoading(false);
      }).catch((e) => disposeErr(e))
    } else {
      if (dataAction.getCreateDefaultValue) {
        dataAction.getCreateDefaultValue().then((data) => {
          setValues(data);
          setLoading(false);
        }).catch((e) => disposeErr(e))
      } else {
        setLoading(false);
      }
    }
  }, []);

  useEffect(() => {
    modalControl.registerOk(() => {
      actionRef.current.getFormData().then((data) => {
        // 更新
        if (rowKey) {
          dataAction.updateItem(rowKey, data).then(() => {
            modalControl.close();
          }).catch((e) => {
            modalControl.hideSaving();
            onError(e.msg || e.message)
          })
        }
        // 创建
        else {
          dataAction.createItem(data).then(() => {
            modalControl.close();
          }).catch((e) => {
            modalControl.hideSaving();
            onError(e.msg || e.message)
          })
        }
      }).catch((e) => {
        modalControl.hideSaving();
        onError(e.msg || e.message)
      });
    });
  });


  return (
    <ProBox loading={loading} errorMsg={errorMsg}>
      {CreateOrEditContent && <CreateOrEditContent ref={actionRef} rowKey={rowKey} values={values} />}
    </ProBox>
  )
};

export default CreateOrEdit;

